# coding=utf-8
# 代码文件：chapter9/ch9.2.4.py
import os

from PyPDF2 import PdfFileReader, PdfFileWriter

#  设置输入目录
indir = r'data\in'
#  设置输出目录
outdir = r'data\out'

infile = os.path.join(indir, 'temp.pdf')

pdfReader = PdfFileReader(infile)
for page_no in range(pdfReader.numPages):
    pdf_writer = PdfFileWriter()
    page = pdfReader.getPage(page_no)
    pdf_writer.addPage(page)

    file = '{0}.pdf'.format(page_no + 1)
    outfile = os.path.join(outdir, file)
    with open(outfile, 'wb') as output_pdf:
        pdf_writer.write(output_pdf)

print('拆分完成。')

pdf_writer = PdfFileWriter()
pdf_writer.addPage(pdfReader.getPage(3))  # 使用原始PDF第4页
pdf_writer.addPage(pdfReader.getPage(0))  # 使用原始PDF第1页添加
pdf_writer.addPage(pdfReader.getPage(2))  # 使用原始PDF第3页添加

file = '4,3,1.pdf'
outfile = os.path.join(outdir, file)
with open(outfile, 'wb') as output_pdf:
    pdf_writer.write(output_pdf)
    print('再次拆分完成。')
